package cn.daniellee.plugin.wl.runnable;

import cn.daniellee.plugin.wl.component.ActionSender;
import cn.daniellee.plugin.wl.WorldLimiter;
import cn.daniellee.plugin.wl.core.LimitCore;
import cn.daniellee.plugin.wl.model.LimitWorld;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;

import java.util.List;
import java.util.Map;
import java.util.Set;

public class LimiterRunnable extends BukkitRunnable {

	@Override
	public void run() {
		for (Map.Entry<String, Integer> entry : LimitCore.tempOpenSecond.entrySet()) {
			int remaining = entry.getValue() - 1;
			if (remaining == 0) LimitCore.tempOpenSecond.remove(entry.getKey());
			else LimitCore.tempOpenSecond.put(entry.getKey(), remaining);
		}
		Location spawnLocation = Bukkit.getWorld(LimitCore.spawnWorld).getSpawnLocation();
		for (LimitWorld limitWorld : LimitCore.limitWorlds) {
			World world = Bukkit.getWorld(limitWorld.getWorldName());
			if (world != null) {
				int remainingSecond = LimitCore.getRemainingSecond(limitWorld);
				if (remainingSecond != 0) {
					if (!limitWorld.isOpening()) {
						WorldLimiter.getInstance().sendBroadcast((WorldLimiter.getInstance().getPrefix() + WorldLimiter.getInstance().getConfig().getString("message.boardcast.open", "&eThe world &b{world} &ehas been opened for a limited time, access method: {way}").replace("{world}", limitWorld.getWorldAlias()).replace("{way}", limitWorld.getWayOfEntry())).replace("&", "§"));
						limitWorld.setOpening(true);
					}
				} else {
					if (limitWorld.isOpening()) {
						WorldLimiter.getInstance().sendBroadcast((WorldLimiter.getInstance().getPrefix() + WorldLimiter.getInstance().getConfig().getString("message.boardcast.close", "&eWorld &b{world} &ehas been temporarily closed, please be patient and wait for the next time.").replace("{world}", limitWorld.getWorldAlias())).replace("&", "§"));
						limitWorld.setOpening(false);
					}
				}
				String remainingAction = WorldLimiter.getInstance().getConfig().getString("message.action-bar.remaining", "&eRemaining: &b{hour}h {minute}m {second}s").replace("{hour}", Integer.toString(remainingSecond / 3600)).replace("{minute}", Integer.toString(remainingSecond % 3600 / 60)).replace("{second}", Integer.toString(remainingSecond % 60)).replace("&", "§");
				for (Player player : world.getPlayers()) {
					if (LimitCore.checkCantEnter(player, limitWorld)) {
						player.teleport(spawnLocation);
					} else {
						if (remainingSecond != 0) ActionSender.send(player, remainingAction);
					}
				}
			}
		}
	}

}
